{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "## 问题： 实例属性的获取和设定上，我们希望增加一些额外的处理过程（比如类型检查或者验证）\n",
    "## 解决： 自定义属性的访问，一种简单的方式是将其定义为property。\n",
    "\n",
    " - 上述代码中，一共有三个互相关联的方法， 它们必须有这相同的名称。\n",
    " - 第一个方法是一个getter 函数，并且将frist_name定义了property属性。\n",
    " - 其他两个方法是可选的。\n",
    " - 除非first_name 已经定义了property属性，否则不能定义first_name.setter first_name.deleter 装饰器。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 注意：　初始化使用的是self.first_name，而getter　和　setter 方法中使用的是self._first_name。\n",
    "\n",
    "\n",
    "class Person:\n",
    "    def __init__(self, first_name):\n",
    "        self.first_name = first_name\n",
    "\n",
    "    # Getter function\n",
    "    @property\n",
    "    def first_name(self):\n",
    "        return self._first_name\n",
    "\n",
    "    # Setter function\n",
    "    @first_name.setter\n",
    "    def first_name(self, value):\n",
    "        if not isinstance(value, str):\n",
    "            raise TypeError('Expected a string')\n",
    "        self._first_name = value\n",
    "\n",
    "    # Deleter function (optional)\n",
    "    @first_name.deleter\n",
    "    def first_name(self):\n",
    "        raise AttributeError(\"Can not delte attribute!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Herbert\n"
     ]
    }
   ],
   "source": [
    "a = Person('Herbert')\n",
    "print(a.first_name)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    ""
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2.0
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}